package com.liujit.auth.security.service;

import com.liujit.auth.domain.result.OauthUser;
import com.liujit.common.domain.result.Result;
import com.liujit.common.enums.ResultCode;
import com.liujit.upms.api.UpmsFeignClient;
import com.liujit.upms.domain.model.SysUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 自定义用户获取方式
 * @Author: liujun
 * @Date: 2021/6/27 10:31 上午
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class OauthUserService implements UserDetailsService {

    private final UpmsFeignClient upmsFeignClient;

    @Override
    public UserDetails loadUserByUsername(String userName) {
        // 根据用户名，获取用户信息
        Result<SysUser> sysUserResult = upmsFeignClient.getByAccount(userName);
        SysUser sysUser = sysUserResult.getData();
        if (sysUser == null || sysUser.getId() == null) {
            log.info("用户不存在：{}", userName);
            throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.msg());
        }
        // 根据用户id，获取角色名
        Result<List<Long>> result = upmsFeignClient.getRoleIdByUserId(sysUser.getId());
        List<Long> roles = result.getData();
        if (roles == null || roles.size() == 0) {
            log.info("用户不存在：{}，没有角色", userName);
            throw new UsernameNotFoundException(ResultCode.USER_NOT_ROLE.msg());
        }
        OauthUser oauthUser = new OauthUser(sysUser, roles);
        if (!oauthUser.isEnabled()) {
            log.info("用户被禁用：{}", userName);
            throw new DisabledException(ResultCode.USER_ACCOUNT_DISABLE.msg());
        }
        return oauthUser;
    }
}
